<script lang="ts" setup>
/** 商品分类级联选择器
 * v-model:categoryId 二级分类id
*/
import type { CascaderOption } from 'naive-ui'
import { categoryGetOne, categoryGetTwo } from '@/api/category'

interface Props {
  categoryId: string | number | null
}
const props = withDefaults(defineProps<Props>(), {
  categoryId: null,
})

const emit = defineEmits(['update:categoryId'])

onMounted(() => {
  getCategory()
})

const categoryData = ref<CascaderOption[]>()

const categoryId = computed({ // 分类双向绑定id
  get() {
    return props.categoryId
  },
  set(val) {
    emit('update:categoryId', val)
  },
})

async function getCategory() { // 获取所有分类数据
  const { data: categoryOne } = await categoryGetOne()
  const { data: categoryTwo } = await categoryGetTwo()

  categoryData.value = categoryOne?.map((item) => {
    const itemData: CascaderOption = {
      label: item.name,
      value: `s${item.id}`, // Naive UI级联选择器bug，父子id会造成冲突，故前缀加上 s+Id
      disabled: false,
      children: [],
    }
    categoryTwo?.forEach((val) => {
      if (item.id === val.parentId) {
        itemData.children?.push({
          label: val.name,
          value: val.id,
          disabled: false,
        })
      }
    })
    return itemData
  })
}
// 最后一级分类筛选回调
function categoryChange(value: number | string) {
  console.log(value, 'value')
  categoryId.value = value
}
</script>

<template>
  <n-cascader
    v-model:value="categoryId"
    clearable
    placeholder="请选择商品类别"
    :options="categoryData"
    check-strategy="child"
    expand-trigger="hover"
    :on-update:value="categoryChange"
    v-bind="$attrs"
  />
</template>
